package com.woniuxy.security.controller;

import com.woniuxy.entity.ResponseResult;
import com.woniuxy.security.util.Audience;
import com.woniuxy.security.util.JwtUtil;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.apache.shiro.SecurityUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/security")
public class UserController {
    @Resource
    private Audience audience;

    @PostMapping("/login")
    public ResponseResult<?> login(String account, String password, HttpServletResponse response){
        //设置令牌携带用户名和密码
        UsernamePasswordToken token = new UsernamePasswordToken(account,password);
        //获取到“当前用户”对象
        Subject subject = SecurityUtils.getSubject();
        try {
            //携带令牌登录验证
            subject.login(token);
        }catch (UnknownAccountException e){
            //抛出UnknownAccountException异常，表示账号异常
            return new ResponseResult<Void>(601,"账号不存在！");
        }catch (AuthenticationException e){
            //AuthenticationException，表示密码异常
            return new ResponseResult<Void>(602,"密码不正确！");
        }
        //登录成功，生成jwt
        String jwt = JwtUtil.createJWT(1,account,audience);
        //将jwt加入返回头
        response.setHeader("Authorization",jwt);
        return ResponseResult.SUCCESS;
    }
}
